﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sireass.Bl.Security;
using System.Web.Security;
using System.Configuration;

namespace Sireass.Asp
{
    public partial class _Default : System.Web.UI.Page
	{
		#region Page
		protected void Page_Load(object sender, EventArgs e)
        {
			if (!IsPostBack)
			{
				bool security = Convert.ToBoolean(ConfigurationManager.AppSettings["Security"]);
				if (security)
				{
					ValidarAutenticacion();
				}
			}
        }
		#endregion

		#region Botones
		protected void rbtnRegPrestador_Click(object sender, EventArgs e)
		{
			Response.Redirect("Administracion/SeguridadPrestadoresServicioSocial.aspx", true);
		}

		protected void rbtnIngresar_Click(object sender, EventArgs e)
		{
			mvwInicio.ActiveViewIndex = 1;
		}

		protected void radBtnLogin_Click(object sender, EventArgs e)
		{
			lblError.Text = "";
			lblExito.Text = "";

			var exito = Login(radTxtUsuario.Text, radTxtPassword.Text);
			if (exito)
			{
				lblExito.Text = "Sesión iniciada correctamente";
				Response.Redirect("Main.aspx", true);
			}
			else
			{
				lblError.Text = "El usuario y/o contraseña no existen o no son correctos";
			}

		}

		protected void radBtnRegresar_Click(object sender, EventArgs e)
		{
			ControlesInicio();
			//mvwInicio.ActiveViewIndex = 0;
		}
		#endregion

		#region Métodos
		protected void ControlesInicio()
		{
			radTxtUsuario.Text = string.Empty;
			radTxtPassword.Text = string.Empty;			
			//radBtnLogin.Text = "Ingresar";
			//ViewState["vwsIdUR"] = null;
		}

		protected bool Login(string username, string password)
		{
			SireassPrincipal.Login(username, password);
			if (Csla.ApplicationContext.User.Identity.IsAuthenticated)
				FormsAuthentication.SetAuthCookie(Csla.ApplicationContext.User.Identity.Name, false);

			return Csla.ApplicationContext.User.Identity.IsAuthenticated;
		}

		protected void ValidarAutenticacion()
		{
			var identity = HttpContext.Current.User.Identity;
			if (identity.IsAuthenticated)
			{
				Response.Redirect("Main.aspx", true);	
			}			
		}
		#endregion
	}
}
